#ifndef MODBUSMANAGER_H
#define MODBUSMANAGER_H

#include <QObject>
#include <qmodbusrtuserialclient.h>
#include <QTimer>
#include <QMap>
#include <QSet>
#include <QSerialPort>

class ModbusManager : public QObject
{
    Q_OBJECT
public:
    explicit ModbusManager(QObject *parent = nullptr);
    ~ModbusManager();

    bool startSimulation(const QString &serialPortName,
                         int baudRate = 9600,
                         int parity = QSerialPort::NoParity,
                         int dataBits = QSerialPort::Data8,
                         int stopBits = QSerialPort::OneStop);
    void stopSimulation();

    void writeCoil(int address, bool value);
    bool isRunning() const;

    // 添加/移除监控的线圈地址
    void addMonitoredCoil(int address);
    void removeMonitoredCoil(int address);
    void setMonitoredCoils(const QSet<int> &addresses);  // 批量设置
    void writeRegister(int address, quint16 value);  // 写入寄存器

signals:
    void coilUpdated(int address, bool value);     // 从站数据更新
    void logMessage(const QString &msg);           // 日志
    // 寄存器更新信号
    void registerUpdated(int address, quint16 value);

private slots:
    void pollModbusCoils();
    // 寄存器轮询方法
    void pollModbusRegisters();

private:
    void sendReadCoilsRequest(int startAddress, int count);

private:
    QModbusClient *modbus_ = nullptr;
    QTimer *coilTimer_ = nullptr;
    bool isRunning_ = false;
    QMap<int, bool> coilValues_;
    // 寄存器轮询定时器
    QTimer *registerTimer_ = nullptr;
    QMap<int, qint16> registerValues_; // 存储寄存器值
    QSet<int> monitoredCoils_;         // 监控的线圈地址集合
    QMap<int, int> monitorRefCounts_;  // 引用计数：地址，被多少组件引用
};

#endif // MODBUSMANAGER_H
